package gw.com.android.ui.quote2;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.quote2.widget.QuoteMenuPopWindow;
import gw.com.android.ui.trade.TradeBusiness;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.android.utils.FontUtils;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.android.utils.PackStatis;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.CommonUtils;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.StringUtils;
import www.com.library.view.PriceTextView;
import www.com.library.view.RecyclerClickListener;

/**
 * 行情产品的适配器
 */
@SuppressWarnings("rawtypes")
public class QuoteProductListAdapter extends RecyclerView.Adapter {

    private final String TAG = QuoteProductListAdapter.this.getClass().getSimpleName();

    public static final int TYPE_FOOTER = 1; // 说明是带有Footer的
    public static final int TYPE_NORMAL = 2; // 说明是不带有header和footer的

    /**
     * 产品布局加载器
     **/
    private LayoutInflater mInflater;
    /**
     * 上下文
     **/
    private BaseActivity mOwnerAct;
    private View mFooterView;//底部
    /**
     * 记录当前是否正在刷新
     */
    private boolean onBind = false;
    private DataItemResult mList;
    private DataItemResult mTmpList;
    private QuoteMenuPopWindow menuPopWindow;

    private String mCurType;
    private QuoteSelfFragment mFragment;

    /**
     * 初始化界面数据
     *
     * @param context
     */
    public QuoteProductListAdapter(QuoteSelfFragment fragment, Context context, String curType) {
        super();
        mFragment = fragment;
        mOwnerAct = (BaseActivity) context;
        mInflater = LayoutInflater.from(context);
        mCurType = curType;
        dispatchData();
        mList = new DataItemResult();
        mList.appendItems(mTmpList);
        Logger.e("curType:" + curType + ";QuoteProductListAdapter   size = " + mList.getDataCount());
    }

    /**
     * 按照条件取数据
     *
     * @return
     */
    private void dispatchData() {
        if (mCurType.equals(GTSConst.ZONE_TYPE_SELF + "")) {
            mTmpList = DataManager.instance().getSelfTickList();
        } else {
            mTmpList = DataManager.instance().getTickList(mCurType);
        }
    }

    /**
     * 刷新界面排序后的数据
     */
    public void refreshSortData() {
        dispatchData();
        mList.clear();
        mList.appendItems(mTmpList);
        if (!onBind) {
            Logger.e("QuoteProductListAdapter   size = " + mList.getDataCount());
            if (mFragment.isFragmentReady()) {
                notifyDataSetChanged();
            } else {
            }
        }
    }


    /**
     * 刷新当前更新的产品报价
     *
     * @param codeId
     */
    public void refreshData(int codeId) {
        if (!onBind) {
            for (int i = 0; i < mList.getDataCount(); i++) {
                final DataItemDetail item = mList.getItem(i);
                if (null != item && item.getInt(GTSConst.JSON_KEY_CODEID) == codeId) {
                    if (mFragment.isFragmentReady()) {
//                        Logger.e("QuoteListAdapter refreshData 更新操作 codeId = " + codeId);
                        notifyItemChanged(i, item);
                    } else {
                    }
                    break;
                }
            }
        }
    }

    @Override
    public int getItemCount() {
        if (mFooterView != null) {
            return null == mList ? 0 : mList.getDataCount() + 1;
        } else {
            return null == mList ? 0 : mList.getDataCount();
        }
    }

    public int getDataCount() {
        return mList == null ? 0 : mList.getDataCount();
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (getItemViewType(position) == TYPE_NORMAL) {
            final DataItemDetail item = getItem(position);
            QuoteItemView viewHolder = (QuoteItemView) holder;
            if (null != item) {
                viewHolder.itemView.setTag(item);

                if (item.getString(GTSConst.JSON_KEY_BUYPRICE).equals("0.0") || item.getString(GTSConst.JSON_KEY_SELLPRICE).equals("0.0")) {
                    setEmptyView(viewHolder);
                    viewHolder.tvProductName.setText(DataManager.instance().getPrdName(item));
                    viewHolder.tvProductSubName.setText(item.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));
                } else {
                    updateViews(viewHolder, item);
                }

                int s = mFooterView == null ? 1 : 2;//如果是倒数第二个item，下划线必须要封闭
                if (position == getItemCount() - s) {//
                    viewHolder.vDivider_18.setVisibility(View.GONE);
                    viewHolder.vDivider_0.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.vDivider_18.setVisibility(View.VISIBLE);
                    viewHolder.vDivider_0.setVisibility(View.GONE);
                }

            } else {
                setEmptyView(viewHolder);
            }
        }

    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position, List payloads) {
        onBind = true;
//		Logger.e("QuoteListAdapter position == " + position + ", "+payloads.isEmpty());
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            if (getItemViewType(position) == TYPE_NORMAL) {
                final DataItemDetail item = (DataItemDetail) payloads.get(0);
                QuoteItemView viewholder = (QuoteItemView) holder;
                if (null != item) {
                    viewholder.itemView.setTag(item);
                    updateViews(viewholder, item);
                }
            }
        }
        onBind = false;
    }

    /**
     * 重写这个方法，很重要，是加入Header和Footer的关键，我们通过判断item的类型，从而绑定不同的view *
     */
    @Override
    public int getItemViewType(int position) {
        if (mFooterView == null) {
            return TYPE_NORMAL;
        }
        if (position == getItemCount() - 1) {
            // 最后一个,应该加载Footer
            return TYPE_FOOTER;
        }
        return TYPE_NORMAL;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup convertView, int viewType) {
        if (mFooterView != null && viewType == TYPE_FOOTER) {
            return new QuoteItemView(mFooterView);
        }
        View v = mInflater.inflate(R.layout.list_item_quote_self, convertView, false);
        return new QuoteItemView(v);
    }

    public DataItemDetail getItem(int position) {
        if (position < 0 || position >= mList.getDataCount()) {
            return null;
        }

        if (null != mList && null != mList.getItem(position)) {
            return mList.getItem(position);
        }

        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private boolean ifTagViewUsed = false;

    /**
     * 更新展示界面数据，主要更新价格部分
     *
     * @param viewHolder
     * @param item       产品对象
     */
    public void updateViews(QuoteItemView viewHolder, final DataItemDetail item) {
//		AppUtil.error("prdName == " + prdName);
        viewHolder.tvProductName.setText(DataManager.instance().getPrdName(item));
        viewHolder.tvProductSubName.setText(AppMain.getAppString(R.string.quote_title_spread,
                item.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME), item.getString(GTSConst.JSON_KEY_DIFF)));

        //产品信息类型，是否为参考行情
        if (item.getInt(GTSConst.JSON_KEY_TRADESTATE) == AppContances.TRADE_STATU_REF || item.getInt(GTSConst.JSON_KEY_ZONE) == GTSConst.ZONE_TYPE_REF) {
            viewHolder.tvProductType.setText("参考");
            viewHolder.tvProductType.setSelected(true);
            viewHolder.tvProductType.setBackgroundDrawable(AppMain.getApp().getResources().getDrawable(R.drawable.common_edittext_bg_selector3));
            viewHolder.tvProductType.setTextColor(mOwnerAct.getResources().getColor(R.color.color_k));
            viewHolder.tvProductType.setVisibility(View.VISIBLE);
            ifTagViewUsed = true;
        } else {
            viewHolder.tvProductType.setVisibility(View.INVISIBLE);
            ifTagViewUsed = false;
        }

        //判断是否为 推荐产品,如果是，就加上推荐标签
        if (!ifTagViewUsed)
            if (DataManager.instance().ifRecommend(item)) {
                viewHolder.tvProductType.setText("推荐");
                viewHolder.tvProductType.setSelected(true);
                viewHolder.tvProductType.setBackgroundDrawable(AppMain.getApp().getResources().getDrawable(R.drawable.common_edittext_bg_selector2));
                viewHolder.tvProductType.setTextColor(mOwnerAct.getResources().getColor(R.color.color_chart_b));
                viewHolder.tvProductType.setVisibility(View.VISIBLE);
            } else {
                viewHolder.tvProductType.setVisibility(View.INVISIBLE);
            }

//		Logger.e("name2 = " + mItem.getString(GTSConst.JSON_KEY_SYMBOLNAMEGB) + mItem.getInt(GTSConst.JSON_KEY_BUYPRICESTATE) + ", " + mItem.getInt(GTSConst.JSON_KEY_SELLPRICESTATE));

        // 卖价
        if (GTConfig.ACC_TYPE_GUEST == GTConfig.instance().getAccountType()
                || item.getString(GTSConst.JSON_KEY_ZOOMRULE).equals("0#0")
                || item.getString(GTSConst.JSON_KEY_ZOOMRULE).equals("#")
                || item.getString(GTSConst.JSON_KEY_ZOOMRULE).equals("")
                || !GTConfig.instance().getBooleanValue(GTConfig.PREF_BIG_QUOTE, false)) {
            viewHolder.tvSellPrice.setText(item.getString(GTSConst.JSON_KEY_SELLPRICE));
        } else {
            viewHolder.tvSellPrice.updateWithPrice(item.getString(GTSConst.JSON_KEY_SELLPRICE), item.getString(GTSConst.JSON_KEY_ZOOMRULE), false);
        }
        viewHolder.tvSellPrice.setBackgroundResource(ColorThemeUtil.instance().getPriceBg(item.getInt(GTSConst.JSON_KEY_SELLPRICESTATE)));

        // 买价
        if (GTConfig.ACC_TYPE_GUEST == GTConfig.instance().getAccountType()
                || item.getString(GTSConst.JSON_KEY_ZOOMRULE).equals("0#0")
                || item.getString(GTSConst.JSON_KEY_ZOOMRULE).equals("#")
                || item.getString(GTSConst.JSON_KEY_ZOOMRULE).equals("")
                || !GTConfig.instance().getBooleanValue(GTConfig.PREF_BIG_QUOTE, false)) {
            viewHolder.tvBuyPrice.setText(item.getString(GTSConst.JSON_KEY_BUYPRICE));
        } else {
            viewHolder.tvBuyPrice.updateWithPrice(item.getString(GTSConst.JSON_KEY_BUYPRICE), item.getString(GTSConst.JSON_KEY_ZOOMRULE), false);
        }
        viewHolder.tvBuyPrice.setBackgroundResource(ColorThemeUtil.instance().getPriceBg(item.getInt(GTSConst.JSON_KEY_BUYPRICESTATE)));

        //仓位数量
        int num = DataManager.instance().getPositionNum(item.getInt(GTSConst.JSON_KEY_CODEID));
        viewHolder.tvProductState.setText(num + "");
        if (num <= 0) {//无仓位
            viewHolder.tvProductState.setVisibility(View.INVISIBLE);
        } else {
            viewHolder.tvProductState.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 设置空数据界面
     */
    private void setEmptyView(QuoteItemView viewHolder) {

        viewHolder.tvProductName.setText(StringUtils.NA_MSG);
        viewHolder.tvProductSubName.setText(StringUtils.NA_MSG);
        viewHolder.tvProductState.setVisibility(View.INVISIBLE);
        viewHolder.tvProductType.setVisibility(View.INVISIBLE);

        // 卖价
        viewHolder.tvSellPrice.setText(StringUtils.NA_MSG);
        viewHolder.tvSellPrice.setTextColor(ColorThemeUtil.instance().color_c);

        // 买价
        viewHolder.tvBuyPrice.setText(StringUtils.NA_MSG);
        viewHolder.tvBuyPrice.setTextColor(ColorThemeUtil.instance().color_c);

    }

    public class QuoteItemView extends ViewHolder {
        @BindView(R.id.ll_product_item)
        public View productItemView;
        @BindView(R.id.product_name)
        public TextView tvProductName;
        @BindView(R.id.product_sub_name)
        public TextView tvProductSubName;
        @BindView(R.id.product_states)
        public TextView tvProductState;
        @BindView(R.id.product_type)
        public TextView tvProductType;
        @BindView(R.id.sell_price)
        public PriceTextView tvSellPrice;
        @BindView(R.id.buy_price)
        public PriceTextView tvBuyPrice;
        @BindView(R.id.v_divider_18)
        public View vDivider_18;
        @BindView(R.id.v_divider_0)
        public View vDivider_0;

        public QuoteItemView(View convertView) {
            super(convertView);
            // 如果是headerview或者是footerview,直接返回
            if (itemView == mFooterView) {
                return;
            }
            ButterKnife.bind(this, convertView);
            productItemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    onMenuClick(v);
                    return true;
                }
            });
            Typeface font = FontUtils.getDIN_MediumFont(mOwnerAct);
            tvSellPrice.setTypeface(font);
            tvBuyPrice.setTypeface(font);
        }

        @OnClick(R.id.ll_product_item)
        void onProductClick() {
            if (CommonUtils.isFastDoubleClick()) {
                return;
            }
            DataItemDetail mTickModel = (DataItemDetail) itemView.getTag();
            if (null == mTickModel) {
                Logger.i("行情数据对象为空！！！");
                showErrorMsg(ConfigType.SERVER_ERROR_1021);
                return;
            }
            MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct, "ClickProduct1");
            PackStatis.getToService(PackStatis.EventAction.CLICKPRODUCT.getValue(), PackStatis.EventCategory.MARKET.getValue(), null, null);
            ActivityManager.showChartActivity(mOwnerAct, mTickModel.getInt(GTSConst.JSON_KEY_CODEID), mTickModel.getInt(GTSConst.JSON_KEY_ZONE), AppContances.TRADE_TYPE_FORM_QUOTE);
        }

        @OnClick(R.id.product_menu)
        void onMenuClick(View view) {
            Logger.i("显示菜单栏信息！！！");
            if (CommonUtils.isFastDoubleClick()) {
                return;
            }
            final DataItemDetail mTickModel = (DataItemDetail) itemView.getTag();

            View clickView = null;
            if (view != null) {
                clickView = view;
            } else {
                clickView = itemView;
            }
            menuPopWindow = new QuoteMenuPopWindow(mOwnerAct, mTickModel, new RecyclerClickListener() {
                @Override
                public void onClick(int position, DataItemDetail itemDetail) {
                    if (itemDetail.getInt("title") == R.string.quote_menu_buy) {
                        onBuyClick(mTickModel);
                    } else if (itemDetail.getInt("title") == R.string.quote_menu_sell) {
                        onSellClick(mTickModel);
                    } else if (itemDetail.getInt("title") == R.string.quote_menu_property) {
                        ActivityManager.showPropertyActivity(mOwnerAct, mTickModel.getInt(GTSConst.JSON_KEY_CODEID),
                                mTickModel.getInt(GTSConst.JSON_KEY_ZONE), DataManager.instance().getPrdName(mTickModel), mTickModel.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));
                    } else if (itemDetail.getInt("title") == R.string.quote_menu_self_add) {
                        if (!NetworkMonitor.hasNetWork()) {
                            return;
                        }
                        mOwnerAct.showToastPopWindow(AppMain.getAppString(R.string.quote_menu_self_add_suc));
                        DataManager.instance().addSelfTick(mTickModel);
                        if (mCurType.equals(GTSConst.ZONE_TYPE_SELF + ""))//如果当前是 自选,才增
                            mList.addItem(mTickModel);
                        AppTerminal.instance().saveCustomer(DataManager.instance().getSelfCodes());
                        notifyDataSetChanged();
                    } else if (itemDetail.getInt("title") == R.string.quote_menu_self_cancel) {
                        if (!NetworkMonitor.hasNetWork()) {
                            return;
                        }
                        mOwnerAct.showToastPopWindow(AppMain.getAppString(R.string.quote_menu_self_cancel_suc));
                        DataManager.instance().removeSelfTick(mTickModel);
                        if (mCurType.equals(GTSConst.ZONE_TYPE_SELF + ""))//如果当前是 自选,,才删
                            mList.removeItem(mTickModel);
                        AppTerminal.instance().saveCustomer(DataManager.instance().getSelfCodes());
                        if (mList.getDataCount() < 1) {
                            RxBus.getInstance().post(GTSConst.REPLY_QUOTE_SELF, mTickModel);
                        }
                        notifyDataSetChanged();
                    }
                }
            });
            MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct, "ClickMenuBS");
            menuPopWindow.showPopup(clickView);
        }

        void onBuyClick(DataItemDetail mTickModel) {
            Logger.i("ll_buy按钮点击了");
            if (!checkTradable(mTickModel)) {
                return;
            }
            PackStatis.getToService(PackStatis.EventAction.CLICKPRODUCTBUY.getValue(), PackStatis.EventCategory.MARKET.getValue(), null, null);
            MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct, "ll_buy");
            ActivityManager.showOrderActivity(mOwnerAct, mTickModel, AppContances.TRADE_TYPE_BUY, AppContances.TRADE_TYPE_FORM_QUOTE);

        }

        void onSellClick(DataItemDetail mTickModel) {
            Logger.i("ll_sell按钮点击了");
            if (!checkTradable(mTickModel)) {
                return;
            }
            PackStatis.getToService(PackStatis.EventAction.CLICKPRODUCTSELL.getValue(), PackStatis.EventCategory.MARKET.getValue(), null, null);
            MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct, "ll_sell");
            ActivityManager.showOrderActivity(mOwnerAct, mTickModel, AppContances.TRADE_TYPE_SALE, AppContances.TRADE_TYPE_FORM_QUOTE);

        }
    }

    /**
     * 下单判断
     *
     * @return
     */
    private boolean checkTradable(DataItemDetail mTickModel) {

        if (null == mTickModel) {
            Logger.i("行情数据对象为空！！！");
            showErrorMsg(ConfigType.SERVER_ERROR_1021);
            return false;
        }

        // 游客登录时弹出提示
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
            GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
            ActivityManager.backLogin(mOwnerAct, false);
            return false;
        }

        if (!TradeBusiness.PreOrderCheck(mOwnerAct, mTickModel.getInt(GTSConst.JSON_KEY_ZONE), mTickModel.getInt(GTSConst.JSON_KEY_TRADESTATE), true, false)) {
            return false;
        }

        return true;
    }

    private void showErrorMsg(String errorId) {
        final PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(mOwnerAct, "", ConfigUtil.instance().getErrorConfigObject().optString(errorId));
        dialog.show();
    }

    public void setMargins(View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

    public View getFooterView() {
        return mFooterView;
    }

    public void setFooterView(View footerView) {
        mFooterView = footerView;
        notifyItemInserted(getItemCount() - 1);
    }

}
